package service

import (
	"entrytask/rpc/config"
	"entrytask/rpc/dal"
	"log"
	"strconv"
	"time"
)

// CacheUserInfo 默认缓存10分钟
func CacheUserInfo(user *dal.User) error {
	err := user.Validate()
	if err != nil {
		panic(err)
	}
	_, err = config.RedisClient.HMSet(redisKey(user.UserName), "username", user.UserName, "nickname", user.Nickname, "profile", user.Profile).Result()
	config.RedisClient.Expire(redisKey(user.UserName), 10*time.Minute)
	return err
}

// GetUserInfo 从缓存中取用户信息
func GetUserInfo(username string) (user *dal.User) {
	nickname, err := config.RedisClient.HGet(redisKey(username), "nickname").Result()
	if err != nil {
		log.Println(err.Error())
		return nil
	}
	profile, err := config.RedisClient.HGet(redisKey(username), "profile").Result()
	if err != nil {
		log.Println(err.Error())
		return nil
	}
	return &dal.User{UserName: username, Nickname: nickname, Profile: profile}
}

func DelUserCache(username string) {
	result, err := config.RedisClient.Del(redisKey(username)).Result()
	if err != nil {
		log.Println("del cache fail for user: ", username + ", del result: " + strconv.FormatInt(result, 10))
	}
}

// CacheTokenForUser 保存用户登录token与用户名的关系
func CacheTokenForUser(token, username string) {
	key := redisKey(token)
	config.RedisClient.Set(key, username, 30*time.Minute)
	log.Printf("cache user login token:%s -> %s", username, key)
}

func GetUserNameFromToken(token string) string {
	key := redisKey(token)
	res, _ := config.RedisClient.Get(key).Result()
	log.Printf("get username from login token: %s -> %s", key, res)
	return res
}

func redisKey(username string) string {
	return "entry:user:" + username
}
